<?php

namespace app\common\model\knowbase;

use app\admin\model\Admin;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Model;
use traits\model\SoftDelete;

class Project extends Model
{

    use SoftDelete;


   
    protected $name = 'knowbase_project';

   
    protected $autoWriteTimestamp = 'integer';

   
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

   
    protected $append = [
        'status_text',
        'access_type_text',
        'archivetime_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
           
           
           
           
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk],'admin_id' => \app\admin\library\Auth::instance()->id]);
            AuthGroupAccess::updateAccess($row[$pk], $row['auth_group_ids']);
            AuthAccess::updateAccess($row[$pk], $row['admin_ids']);
            if (strpos(request()->url(), '/cloneone')!==false){
                $str = '_'.__('btn_clone');
                $title = preg_replace("/{$str}/", "", $row['title'],1);
                Progress::addLog('project_clone',request()->param('ids'),$title);
            } else {
                Progress::addLog('project_add', $row[$pk], $row['title']);
            }
        });

        self::afterUpdate(function ($row) {
            self::handleAfterUpdate($row);
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
        });

        self::afterDelete(function ($row) {
           
           
           
           
            if ($row->deletetime > 0 && time() - $row->deletetime <= 1) {
               
                Progress::addLog('project_soft_delete', $row['id'], $row['title']);
            } else {
               
                Progress::addLog('project_hard_delete', $row['id'], $row['title']);
            }
        });

    }

    public static function handleAfterUpdate(&$row)
    {
        if (strpos(request()->url(), '/knowbase/document')!==false){
            return;
        }

       
       
       
       
        
       
        static $isUpdate = 0;
        if (!$isUpdate) {
            $pk = $row->getPk();
            AuthGroupAccess::updateAccess($row[$pk], $row['auth_group_ids']);
            AuthAccess::updateAccess($row[$pk], $row['admin_ids']);
            if (request()->post('row.sync_switch', 0, 'intval')) {
                ProjectPage::where('knowbase_project_id', $row[$pk])->update(['access_type' => 4]);
            }
            if ($row->origin['archive_switch'] && !$row['archive_switch']) {
               
                $row->where('id', $row['id'])->update(['archivetime' => 0]);
            } else if (!$row->origin['archive_switch'] && $row['archive_switch']) {
               
                $row->where('id', $row['id'])->update(['archivetime' => time()]);
            }
            if (strpos(request()->url(), '/project/cloneone/')===false){
                if (strpos(request()->url(), '/ajax/weigh') !== false) {
                    Progress::addLog('project_weight', $row['id'], $row['title'] . '，排序值:' . $row['weigh']);
                } else if (strpos(request()->url(), '/restore') !== false) {
                    Progress::addLog('project_restore', $row['id'], $row['title']);
                } else if (strpos(request()->url(), '/del') === false && strpos(request()->url(), '/add') === false) {
                    Progress::addLog('project_update', $row['id'], $row['title']);
                }
            }
            $isUpdate = 1;
        }

    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }

    public function getAccessTypeList()
    {
        return ['0' => __('Access_type 0'), '1' => __('Access_type 1'), '2' => __('Access_type 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list  = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getAccessTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['access_type']) ? $data['access_type'] : '');
        $list  = $this->getAccessTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getArchivetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['archivetime']) ? $data['archivetime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setArchivetimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function admin()
    {
        return $this->belongsTo(Admin::class, 'admin_id')->setEagerlyType(0);
    }

    public function groups()
    {
        return $this->hasMany(AuthGroupAccess::class, 'project_id');
    }

    public function auths()
    {
        return $this->hasMany(AuthAccess::class, 'project_id');
    }


    public function checkAccess()
    {
        if (\app\admin\library\Auth::instance()->isSuperAdmin()) {
            return true;
        }
        $admin_ids  = array_filter(explode(",", $this->getData('admin_ids')));
        $auth_group_ids  = array_filter(explode(",", $this->getData('auth_group_ids')));
        $groups = array_column(\app\admin\library\Auth::instance()->getGroups(),'group_id');
        if (!$admin_ids && !$auth_group_ids) {
            return true;
        }
        if (in_array(\app\admin\library\Auth::instance()->id, $admin_ids) || array_intersect($auth_group_ids, $groups)) {
            return true;
        }
        return false;
    }

    public static function getHotPages()
    {
        if (Cache::tag('knowbase')->has('getHotPages')) {
            return Cache::tag('knowbase')->get('getHotPages');
        } else {
            $data =  collection(self::where('p.status','1')->alias('p')
                ->join('knowbase_project_page p2','p.id=p2.knowbase_project_id')
                ->where('p2.status_switch','1')
                ->where('p2.type','file')
                ->field('p.id,p.title,p.identify,p2.knowbase_project_id,p2.id as page_id,p2.title as page_title,p2.identify as page_identify,p2.updatetime')
                ->order('p2.updatetime desc')
                ->limit(1000)
                ->select())
                ->toArray();
            foreach ($data as &$v){
                if ($v['identify']) {
                    $v['url'] = str_replace(['{0}','{1}'], [$v['identify'],$v['page_identify']??$v['page_id']], config('url_knowbase_rewrite_page') );
                } else {
                    $v['url'] = str_replace('{0}', $v['page_id'], config('url_knowbase_page') );
                }
                $date = date('Y-m-d H:i:s',$v['updatetime']);
                $dateTime = new \DateTime($date, new \DateTimeZone('Asia/Shanghai'));
                $v['time'] = $dateTime->format('Y-m-d\TH:i:sP');
                unset($v);
            }
            Cache::tag('knowbase')->set('getHotPages',$data,3600);
            return $data;
        }
    }
    
    public function cloneone($id)
    {
        $row = $this->get($id);
        if (!$row) {
            $this->error = __('error_not_record');
            return false;
        } else if (!$row->checkAccess()) {
            $this->error(__('tips_not_access'));
        }
        $data = $row->getData();
        unset($data['id']);
        unset($data['update_time']);
        unset($data['create_time']);
        unset($data['identify']);

        $data['title'] = $data['title'] . '_' . __('btn_clone');
        
        $pages         = knowbase_groupbyid(array_map(function ($v){
            return $v->getData();
        }, ProjectPage::where('knowbase_project_id', $id)->select()) ) ;
        $pages = array_filter(knowbase_generate_tree($pages),function ($v){
           
            return $v['pid']==0;
        });
        set_time_limit(0);
        Db::startTrans();
        try {
            $project = \app\common\model\knowbase\Project::create($data);
            $new_id      = $project->id;
            $this->clonePages($pages, $new_id);  
            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }

        return true;
    }

   
    protected function clonePages($originalPages, $newShopId,$parent_id=0)
    {
        foreach ($originalPages as $originalPage) {
           
            $newPageId = $this->insertClonedPage($originalPage, $newShopId,$parent_id);
           
            if (isset($originalPage['son']) && $originalPage['son']) {
                $this->clonePages($originalPage['son'], $newShopId,$newPageId);
            } 
        }
    }

   
    protected function insertClonedPage($originalPage, $newShopId,$parent_id=0) {
        unset($originalPage['id']);
        unset($originalPage['update_time']);
        unset($originalPage['create_time']);
        unset($originalPage['nodes']);
        unset($originalPage['son']);
        $originalPage['knowbase_project_id'] = $newShopId;
        $originalPage['pid'] = $parent_id;
        $originalPage['admin_id'] =\app\admin\library\Auth::instance()->id;
        $obj = ProjectPage::create($originalPage);
        return $obj->id;
    }
    
}
